package com.example.tao.mybroadcast;

import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity implements IOnChangeText{

    private Button but1;
    private Button but2;
    private TextView tx1;
    private MyBroadcastReceiver receiver;
    private IntentFilter intentFilter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        but1 = findViewById(R.id.button);
        but2 = findViewById(R.id.button2);
        tx1 = findViewById(R.id.textView);

        but1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiver = new MyBroadcastReceiver();
                receiver.setOnChangeText(MainActivity.this);
                //动态接受网络变化的广播接收器
                intentFilter = new IntentFilter();
                intentFilter.addAction(Intent.ACTION_TIME_TICK);
                intentFilter.addAction(Intent.ACTION_TIME_CHANGED);
                registerReceiver(receiver,intentFilter);
            }
        });

        but2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                receiver = new MyBroadcastReceiver();
                receiver.setOnChangeText(MainActivity.this);
                //动态接受网络变化的广播接收器
                intentFilter = new IntentFilter();
                intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
                registerReceiver(receiver,intentFilter);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在适当的时候要解除广播接收者的绑定
        unregisterReceiver(receiver);
    }

    @Override
    public void setText(String text) {
        tx1.setText(text);
    }

    @Override
    public void setTime() {
        final Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);

        boolean is24hFormart = true;
        if (!is24hFormart && hour >= 12) {
            hour = hour - 12;
        }

        String time = "";
        if (hour >= 10) {
            time += Integer.toString(hour);
        }
        else {
            time += "0" + Integer.toString(hour);
        }
        time += ":";

        if (minute >= 10) {
            time += Integer.toString(minute);
        }
        else {
            time += "0" + Integer.toString(minute);
        }

        tx1.setText(time);
    }


}
